const mysql=require('mysql');
module.exports={
  login(req,res){
    // let usersOpt=[
    //   {email:'317009160@qq.com',pwd:"1234"},
    //   {email:'695811447@qq.com',pwd:"1245"},
    //   {email:'wuxingshi97@qq.com',pwd:"168"},
    // ];
    let useremail='';
    let password='';
    if (req.method=='POST'){
       useremail=req.body.useremail;
       password=req.body.password;
    }else if(req.method=='GET'){
       useremail=req.query.useremail; //这个是form表单提交 input name='username', url就会传递自动携带,用query
       password=req.query.password;
    }
    console.log(useremail);
    console.log(password);
    let db=mysql.createConnection({
      host:'localhost',
      port:'3306',
      user:'root',
      password:'mWXS19971222@.',
      database:'sequelize'
    })
    db.connect();
    db.query("SELECT * FROM users WHERE useremail=? AND password=?",[useremail,password],function (err,data) {
      if (data.length>0){
        res.send(data[0].username+'登录成功');
      }else {
        res.send('登录失败');
      }
    });
    db.end();

    // for (let i = 0; i < usersOpt.length; i++) {
    //   if (usersOpt[i].email==useremail&&usersOpt[i].pwd==password){
    //     res.send('login success');
    //     return
    //   }else{
    //     res.send('login failure');
    //     return;
    //   }
    // }
  },
  register(req,res){
    // 1.拿到前台传递过来的数据
    let {useremail,userpassword}=req.body
    // 2.将数据写入数据库
    // 2.1创建数据库连接
    let db=mysql.createConnection({
      host:'localhost',
      port:'3306',
      user:'root',
      password:'mWXS19971222@.',
      database:'sequelize'
    })
    // 2.2打开数据库连接
    db.connect()
    // 2.3操作数据库
    db.query('insert into users values(null,null,null,null,?,?)',[userpassword,useremail],function (err,data) {
      // 2.3.1配置相应的sq1语句和参数
      // 2.3.2数据写入争取需要干什么,错误需要干什
      if (data!=undefined){ //操作成功
        res.redirect('/page/index.html')
      }else {
        res.send('注册失败了....')
      }
    })
    // 2.4关闭数据库
    db.end()
  }
}